﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Cryptography;
using System.Text;

namespace BlazorAdmin.Web.Shared.Filter
{
    /// <summary>
    /// 登录验证
    /// </summary>
    public class AuthToken : ActionFilterAttribute, IAuthorizationFilter
    {
        private readonly TimeSpan timeoutTime = new(0, 30, 0);
        private readonly Func<object, string?, string> tokenFun;
        /// <summary>
        /// 
        /// </summary>
        public AuthToken()
        {
            tokenFun = new Func<object, string?, string>((k, p) =>
            {
                string token = $"HRCSWebAPI-{k}-{p}";
                using (MD5 md5 = MD5.Create())
                {
                    byte[] array = md5.ComputeHash(Encoding.ASCII.GetBytes(token));
                    token = BitConverter.ToString(array).Replace("-", "");
                }
                return token;
            });
        }
        /// <summary>
        /// WebApi请求密码
        /// </summary>
        public static string? WebApiPassword { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //context.HttpContext.User.AddIdentity()
            base.OnActionExecuting(context);
        }
        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (!IsAuthorization(filterContext, out string message))
            {
                filterContext.Result = new JsonResult(message);
                filterContext.HttpContext.Response.StatusCode = 214;
            }
            //filterContext.HttpContext.Response.StatusCode = ResponseStatusCode
            //string cActionName = filterContext.ActionDescriptor.ActionName;
            //string cControlName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            //if (HttpContext.Current.Session["usercode"] == null)
            //{
            //    if (!HttpContext.Current.Request.IsAuthenticated && ("index" != cActionName.ToLower() || "login" != cControlName.ToLower()))
            //    {
            //        HttpContext.Current.Session.Add("IsRedirect", true);
            //        filterContext.Result = new EmptyResult();
            //        filterContext.HttpContext.Response.Redirect("~/Login/Index", true);
            //    }
            //}
        }

        private bool IsAuthorization(AuthorizationFilterContext filterContex, out string message)
        {//暂时启用此类安全验证
            message = string.Empty;
            var headers = filterContex.HttpContext.Request.Headers;
            string userCode = string.Empty;
            string uToken = string.Empty;
            if (headers.ContainsKey("UserCode"))
                userCode = headers["UserCode"].ToString();
            if (headers.ContainsKey("Token"))
                uToken = headers["Token"].ToString();
            if (string.IsNullOrEmpty(userCode))
            {
                message = "Header中缺少UserCode";
                return false;
            }
            if (string.IsNullOrEmpty(uToken))
            {
                message = "Header中缺少Token";
                return false;
            }

            string? pwd = WebApiPassword;
            //string token = MemoryCacheHelper.Find(userCode, tokenFun, timeoutTime, ExpirationType.Sliding, pwd);
            //if (!token.Equals(uToken))
            //{
            //    message = "Token验证失败";
            //    return false;
            //}
            return true;
        }
    }
}
